package com.example.demo.service.impl;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public User findByUsername(String username) {

		return userRepository.findByUsername(username);
	}

	@Override
	public User register(User entity) throws Exception {
		if (StringUtils.isEmpty(entity.getRealname()) || StringUtils.isEmpty(entity.getUsername())) {
			throw new Exception("账号和姓名不能为空");
		}
		User user = userRepository.findByUsername(entity.getUsername());
		if (user != null) {
			throw new Exception("账号被占用");
		}
		entity.setId(UUID.randomUUID().toString().replace("-", ""));
		entity.setPassword("123456");
		entity.setIsDelete("0");
		userRepository.insert(entity);
		return entity;
	}

	@Override
	public void saveOrUpdate(User entity) throws Exception {
		if (StringUtils.isEmpty(entity.getId())) {
			register(entity);
		} else {
//			userRepository.save(entity);// 如果参数中包含主键则update
			updateNotNull(entity);
		}
	}

	@Override
	public void deleteLogic(Object key) throws Exception {
		User user = userRepository.findById(key.toString()).get();
		if (user == null) {
			throw new Exception("数据不存在");
		}
		if ("admin".equals(user.getUsername())) {
			throw new Exception("不能删除admin用户");
		}
		user.setIsDelete("1");
		userRepository.save(user);
	}
/*
	@Override
	public void updateNotNull(User entity) {
		Optional<User> userOptional = userRepository.findById(entity.getId());
		User user = userOptional.get();
		Field[] fields = user.getClass().getDeclaredFields();
		for(int i=0;i<fields.length;i++) {
			Field field = fields[i];
			field.setAccessible(true);
			String fieldName = field.getName();
			if("serialVersionUID".equals(fieldName) || "_id".equals(fieldName) || "id".equals(fieldName)) {
				continue;
			}
			try {
				Object fieldValue = field.get(entity);
				System.out.println("fieldName = "+fieldName+"，value="+fieldValue);
				if(!StringUtils.isEmpty(fieldValue)) {
					field.set(user, fieldValue);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		userRepository.save(user);
	}
*/
}
